package org.jeecg.modules.third.digitalseal.service;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.digitalseal.utils.PdfEditUtil;
import org.jeecg.modules.third.digitalseal.utils.PdfToImageUtil;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerCompany;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerCompanyService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.modules.third.digitalseal.utils.PdfEditUtil.*;

/**
 * @Description: 电子签章服务
 * @author: luruirui
 * @date: 2021年04月19日 9:59
 */
@Service
@Slf4j
public class DigitalSignetService {
    private final Logger logger = LoggerFactory.getLogger(DigitalSignetService.class);

    @Autowired
    private IHySettingService settingService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private IHySettingService hySettingService;

    @Autowired
    private IHyCustomerCompanyService hyCustomerCompanyService;

    @Autowired
    private IHyCompanyService hyCompanyService;



    private String PATH_SUBFIX;//路径前缀
    private String VEHICLE_TEMPLATE_PATH;//车辆挂靠声明模板
    private String SHIPPING_TEMPLATE_PATH;//运输协议模板
    private String OFFICIAL_SEAL;//合同章

    //文件保存地址路径
    private String SAVE_CONTRACT_ADDR = "documents" + File.separator  +  DateUtils.getDate("yyyyMMdd")+ File.separator;
    //PDF后缀
    private String PDF_SUFFIX = ".pdf";
    //司机签名文件名前缀
    private String SIGNET_NAME_SUBFIX = "司机签名_";
    //车辆挂靠声明文件名前缀
    private String VEHICLE_NAME_SUBFIX = "车辆挂靠声明_";
    //运输协议文件名前缀
    private String SHIPPING_NAME_SUBFIX= "运输协议_";

    private String SHIPPING_NAME_LXTAX = "税务协议_";


    /*@Value(value = "${mabang-contract.appKey}")
    private String appKey;

    @Value(value = "${mabang-contract.secrept}")
    private String secrept;*/



    @PostConstruct
    public void init(){
        PATH_SUBFIX = uploadpath + File.separator ;
        //PATH_SUBFIX = "c:\\opt\\upFiles" + File.separator;
//        logger.info("init 路径前缀：{}", PATH_SUBFIX);

       /* HyConfig gasConfig = HyConfigUtils.getConfig();
        if(gasConfig != null && gasConfig.getYyzContractIzUse()){
            //初始化易云章应用配置
            EcloudPublicKey.init(gasConfig.getYyzContractAppkey(), gasConfig.getYyzContractSecrept(), "1.0",
                    StringUtils.EMPTY);
        }*/

    }

    //起草税务声明
    public String draftTaxContract(HyDriver driver){
        VEHICLE_TEMPLATE_PATH = PATH_SUBFIX + settingService.getSettingValueByTag("driver_tax_template");
        String footer_company_name = settingService.getSettingValueByTag("footer_company_name");
//        logger.info("init 车辆挂靠声明模板模板路径：{}", VEHICLE_TEMPLATE_PATH);

        //根据前端设置拿到水印
        String driver_shipping_template_watermark = settingService.getSettingValueByTag("driver_shipping_template_watermark");
//        logger.info("获取前端挂靠声明水印",driver_shipping_template_watermark);

        String contractPath = "";
        try {
            // Loading an existing document
            //InputStream inFile = DigitalSignetService.class.getClassLoader().getResourceAsStream(VEHICLE_TEMPLATE_PATH);
            //ClassPathResource classPathResource = new ClassPathResource(VEHICLE_TEMPLATE_PATH);
            //InputStream inFile =classPathResource.getInputStream();
            File inFile = new File(VEHICLE_TEMPLATE_PATH);
//            logger.info("draftVehicleContract: 模板地址|{}", VEHICLE_TEMPLATE_PATH);
            PDDocument document = PDDocument.load(inFile);
            //添加水印-----
            PdfEditUtil.addWaterMark(document,driver_shipping_template_watermark);
            //第一页
            PDPageContentStream contentStream = getPDPageContentStream(document, 0);
            //添加司机姓名
            showTextByLeft(contentStream, driver.getDriverName(), "", 185,675);
            //添加司机身份证号
            showTextByLeft(contentStream, driver.getIdcard(), "", 340,675);

            //添加日期
            String dateFormat = DateUtils.getDate("yyyy年MM月dd日");
            showTextByLeft(contentStream, dateFormat, "", 300,322);
            //添加委托人
            showTextByLeft(contentStream, footer_company_name+"办税人员", "", 170,640);
            //添加司机签名
            //PdfEditUtil.addImage(contentStream, document, "C:\\opt\\upFiles\\signet\\1618799611572.png", 130, 310);
//            System.out.println("Content added");

            // Closing the content stream
            contentStream.close();

            String path = PATH_SUBFIX + SAVE_CONTRACT_ADDR;
            File fileDir = new File(path);
            if(!fileDir.exists()) {
                fileDir.mkdirs();//创建目录
            }
            contractPath = SAVE_CONTRACT_ADDR + VEHICLE_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
            String filename = PATH_SUBFIX + contractPath;

//            logger.info("draftVehicleContract: path|{}", path);
//            logger.info("draftVehicleContract: contractPath|{}", contractPath);
//            logger.info("draftVehicleContract: filename|{}", filename);

            // Saving the document
            document.save(new File(filename));
            // Closing the document
            document.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return contractPath;
    }

    //起草车辆挂靠声明
    public String draftVehicleContract(HyDriver driver, String vehicleNumber, String companyName){
        VEHICLE_TEMPLATE_PATH = PATH_SUBFIX + settingService.getSettingValueByTag("vehicle_hang_template");
//        logger.info("init 车辆挂靠声明模板模板路径：{}", VEHICLE_TEMPLATE_PATH);

        //根据前端设置拿到水印
        String driver_shipping_template_watermark = settingService.getSettingValueByTag("driver_shipping_template_watermark");
//        logger.info("获取前端挂靠声明水印",driver_shipping_template_watermark);

        String contractPath = "";
        try {
            // Loading an existing document
            //InputStream inFile = DigitalSignetService.class.getClassLoader().getResourceAsStream(VEHICLE_TEMPLATE_PATH);
            //ClassPathResource classPathResource = new ClassPathResource(VEHICLE_TEMPLATE_PATH);
            //InputStream inFile =classPathResource.getInputStream();
            File inFile = new File(VEHICLE_TEMPLATE_PATH);
//            logger.info("draftVehicleContract: 模板地址|{}", VEHICLE_TEMPLATE_PATH);
            PDDocument document = PDDocument.load(inFile);
            //添加水印-----
            PdfEditUtil.addWaterMark(document,driver_shipping_template_watermark);
            //第一页
            PDPageContentStream contentStream = getPDPageContentStream(document, 0);
            //添加司机姓名
            showTextByLeft(contentStream, driver.getDriverName(), "", 165,700);
            //添加司机身份证号
            showTextByLeft(contentStream, driver.getIdcard(), "", 320,700);
            //添加车牌号
            showTextByLeft(contentStream, vehicleNumber, "", 100,668);
            //添加挂靠公司
            showTextByLeft(contentStream, companyName, "", 260,638);

            //添加日期
            String dateFormat = DateUtils.getDate("yyyy年MM月dd日");
            showTextByLeft(contentStream, dateFormat, "", 150,322);
            //添加司机身份证号
            showTextByLeft(contentStream, driver.getIdcard(), "", 150,354);
            //添加司机签名
            //PdfEditUtil.addImage(contentStream, document, "C:\\opt\\upFiles\\signet\\1618799611572.png", 130, 310);
//            System.out.println("Content added");

            // Closing the content stream
            contentStream.close();

            String path = PATH_SUBFIX + SAVE_CONTRACT_ADDR;
            File fileDir = new File(path);
            if(!fileDir.exists()) {
                fileDir.mkdirs();//创建目录
            }
            contractPath = SAVE_CONTRACT_ADDR + VEHICLE_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
            String filename = PATH_SUBFIX + contractPath;

//            logger.info("draftVehicleContract: path|{}", path);
//            logger.info("draftVehicleContract: contractPath|{}", contractPath);
//            logger.info("draftVehicleContract: filename|{}", filename);

            // Saving the document
            document.save(new File(filename));
            // Closing the document
            document.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return contractPath;
    }
    //起草运输协议 方法已作废
    public String draftShippingContract(){
        SHIPPING_TEMPLATE_PATH = PATH_SUBFIX + settingService.getSettingValueByTag("driver_shipping_template");
        OFFICIAL_SEAL = PATH_SUBFIX + settingService.getSettingValueByTag("digital_seal_img");
//        logger.info("init 运输协议模板路径：{}", SHIPPING_TEMPLATE_PATH);
//        logger.info("init 公章路径：{}", OFFICIAL_SEAL);

        String contractPath = "";
        try {
            // Loading an existing document
            //InputStream inFile = DigitalSignetService.class.getClassLoader().getResourceAsStream(SHIPPING_TEMPLATE_PATH);
            File inFile = new File(SHIPPING_TEMPLATE_PATH);
//            logger.info("draftShippingContract: 模板地址|{}", SHIPPING_TEMPLATE_PATH);
            PDDocument document = PDDocument.load(inFile);
            //添加水印
            String watermark = "11223";
            PdfEditUtil.addWaterMark(document,watermark);
            //第4页添加文字
            PDPageContentStream page4ContentStream = getPDPageContentStream(document, 3);

            //获取时间加一年
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR, 1);//增加一年
            cal.add(Calendar.DATE, -1);//减一天   
            //cd.add(Calendar.MONTH, n);//增加一个月

            // 截止日期 年月日
            showTextByLeft(page4ContentStream, cal.get(Calendar.YEAR) + "", "", 360,94);
            showTextByLeft(page4ContentStream, (cal.get(Calendar.MONTH) + 1) + "", "", 418,94);
            showTextByLeft(page4ContentStream, cal.get(Calendar.DAY_OF_MONTH) + "", "", 456,94);
            page4ContentStream.close();
//            System.out.println("Page4 Content added");

            String dateFormat = DateUtils.getDate("yyyy年MM月dd日");
            //第5页添加内容
            PDPageContentStream page5ContentStream = getPDPageContentStream(document, 4);
            //添加甲方签订日期
            showTextByLeft(page5ContentStream, dateFormat, "", 155,655);
            //添加乙方签订日期
            showTextByLeft(page5ContentStream, dateFormat, "", 422,655);
            //添加甲方单位公章
            //ClassPathResource classPathResource = new ClassPathResource(OFFICIAL_SEAL);
            //File file = classPathResource.getFile();
            //PdfEditUtil.addImage(page5ContentStream, document, file.getPath(), 130, 620);
            addImage(page5ContentStream, document, OFFICIAL_SEAL, 130, 620);
            //添加乙方单位公章
            //PdfEditUtil.addImage(page5ContentStream, document, OFFICIAL_SEAL, 402, 620);
            // Closing the content stream
            page5ContentStream.close();
//            System.out.println("Page5 Content added");


            String path = PATH_SUBFIX + SAVE_CONTRACT_ADDR;
            File fileDir = new File(path);
            if(!fileDir.exists()) {
                fileDir.mkdirs();//创建目录
            }
            contractPath = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
            String filename = PATH_SUBFIX + contractPath;
//            logger.info("draftShippingContract: path|{}", path);
//            logger.info("draftShippingContract: contractPath|{}", contractPath);
//            logger.info("draftShippingContract: filename|{}", filename);
            // Saving the document
            document.save(new File(filename));
            // Closing the document
            document.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return contractPath;
    }

    public String checkShippingContract() {
        return File.separator + settingService.getSettingValueByTag("driver_shipping_template");
    }

    //起草运输协议（带部分货源信息）
    public String draftShippingContract(JSONObject joOrder){
        SHIPPING_TEMPLATE_PATH = PATH_SUBFIX + settingService.getSettingValueByTag("driver_shipping_template");
//        OFFICIAL_SEAL = PATH_SUBFIX + settingService.getSettingValueByTag("digital_seal_img");
//        OFFICIAL_SEAL = PATH_SUBFIX + settingService.getSettingValueByTag("digital_seal_img");
//        logger.info("init 运输协议模板路径：{}", SHIPPING_TEMPLATE_PATH);
//        logger.info("init 公章路径：{}", OFFICIAL_SEAL);

        //根据前端设置拿到水印
        String driver_shipping_template_watermark = settingService.getSettingValueByTag("driver_shipping_template_watermark");
//        logger.info("模板水印",driver_shipping_template_watermark);

        String contractPath = "";
        try {
            String customerId = joOrder.getString("customerId");

            HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(customerId);
            if(customerCompany==null){
                log.error("货主未绑定分公司! {}", joOrder);
                throw new Exception("货主未绑定分公司!");
            }
            HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
            if(company==null){
                log.error("分公司信息不存在! {}", joOrder);
                throw new Exception("分公司信息不存在!");
            }
            if(StringUtils.isEmpty(company.getElectronicSeal())){
                log.error("请配置分公司电子公章! {}", joOrder);
                throw new Exception("请配置分公司电子公章!");
            }

            log.info("----- {}, {}",SHIPPING_TEMPLATE_PATH, customerId);
            // Loading an existing document
            //InputStream inFile = DigitalSignetService.class.getClassLoader().getResourceAsStream(SHIPPING_TEMPLATE_PATH);
            File inFile = new File(SHIPPING_TEMPLATE_PATH);
//            logger.info("draftShippingContract: 模板地址|{}", SHIPPING_TEMPLATE_PATH);
            PDDocument document = PDDocument.load(inFile);
            //添加水印----
            PdfEditUtil.addWaterMark(document,company.getCompanyName());

            String dateFormat = DateUtils.getDate("yyyy年MM月dd日");
            //log.info("1111111111111111111----- {}, {}",SHIPPING_TEMPLATE_PATH, customerId);
            //第1页添加内容
            PDPageContentStream pageContentStream1 = getPDPageContentStream(document, 0);

//            String qiyexinxi=hySettingService.getSettingValueByTag("driver_shipping_template_watermark");
            OFFICIAL_SEAL = PATH_SUBFIX + company.getElectronicSeal();
            //甲方
            showTextByLeft(pageContentStream1,  company.getCompanyName(), "", 150,675);

            pageContentStream1.close();
            //log.info("2222222222222222----- {}, {}",SHIPPING_TEMPLATE_PATH, customerId);
            //第4页添加内容
            PDPageContentStream pageContentStream = getPDPageContentStream(document, 3);

            showTextByLeft(pageContentStream, joOrder.getString("orderNum"), "", 200,200 );
            //添加货物名称
            showTextByLeft(pageContentStream, joOrder.getString("descriptionOfGoods"), "", 200,170 );
            //添加货物总重量
            String goodsWeight = joOrder.getString("totalGoodsWeight") + joOrder.getString("goodsUnit_dictText");
            if(joOrder.getString("totalGoodsWeight")==null){
                showTextByLeft(pageContentStream, "-", "", 415,170 );
            }else{
                showTextByLeft(pageContentStream, goodsWeight, "", 415,170 );
            }
            //log.info("33333333333333333333----- {}, {}",SHIPPING_TEMPLATE_PATH, customerId);
            //添加运费计算方式
            showTextByLeft(pageContentStream, joOrder.getString("shippingType_dictText"), "", 200,140 );
            //添加运费单价
//            String goodsPrice = joOrder.getString("shippingUnitPrice") + "元/" + joOrder.getString("goodsUnit_dictText");
            String goodsPrice = joOrder.getString("shippingUnitPrice")+ "元";
            showTextByLeft(pageContentStream, goodsPrice, "", 415,140 );
            //添加亏损货物单价
//            String lossPrice = joOrder.getString("lossGoodsUnitPrice") + "元/" + joOrder.getString("goodsUnit_dictText");
            String lossPrice = joOrder.getString("lossGoodsUnitPrice") + "元";
            showTextByLeft(pageContentStream, lossPrice, "", 200,110 );
            //添加亏损免赔设置
            double lossProportion = joOrder.getDouble("lossProportion");
            String result = String.format("%.3f", lossProportion);
            String txt = joOrder.getString("lossType_dictText") + result;
            showTextByLeft(pageContentStream, txt, "", 415,110 );
            //装货时间
            showTextByLeft(pageContentStream, dateFormat, "", 200,75 );
            // Closing the content stream
            pageContentStream.close();

            //log.info("44444444444444444444444444444----- {}, {}",SHIPPING_TEMPLATE_PATH, customerId);
            //第5页添加内容
            PDPageContentStream pageContentStream2 = getPDPageContentStream(document, 4);

            //添加甲方单位公章
            addImage(pageContentStream2, document, OFFICIAL_SEAL, 130, 690);
            //添加乙方单位公章
//            addImage(pageContentStream2, document, "D:\\Administrator\\桌面\\123.jpg", 382, 690);
            //添加甲方签订日期
            showTextByLeft(pageContentStream2, dateFormat, "", 155,720);
            //添加乙方签订日期
            showTextByLeft(pageContentStream2, dateFormat, "", 408,720);

            // Closing the content stream
            pageContentStream2.close();

            String path = PATH_SUBFIX + SAVE_CONTRACT_ADDR;
            File fileDir = new File(path);
            if(!fileDir.exists()) {
                fileDir.mkdirs();//创建目录
            }
            contractPath = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
            String filename = PATH_SUBFIX + contractPath;
//            logger.info("draftShippingContract: path|{}", path);
//            logger.info("draftShippingContract: contractPath|{}", contractPath);
//            logger.info("draftShippingContract: filename|{}", filename);
            // Saving the document
            document.save(new File(filename));
            // Closing the document
            document.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return contractPath;
    }

    //起草运输协议（带部分货源信息）
    public String draftShippingContract2(JSONObject joOrder,HyShippingNote shippingNote){
        SHIPPING_TEMPLATE_PATH = PATH_SUBFIX + settingService.getSettingValueByTag("driver_shipping_template");
//        OFFICIAL_SEAL = PATH_SUBFIX + settingService.getSettingValueByTag("digital_seal_img");
//        logger.info("init 运输协议模板路径：{}", SHIPPING_TEMPLATE_PATH);
//        logger.info("init 公章路径：{}", OFFICIAL_SEAL);

        //根据前端设置拿到水印
//        String driver_shipping_template_watermark = settingService.getSettingValueByTag("driver_shipping_template_watermark");
//        logger.info("模板水印",driver_shipping_template_watermark);

        String contractPath = "";
        try {
            String customerId = joOrder.getString("customerId");

            HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(customerId);
            if(customerCompany==null){
                throw new Exception("货主未绑定分公司!");
            }
            HyCompany company = hyCompanyService.getById(customerCompany.getCompanyId());
            if(company==null){
                throw new Exception("分公司信息不存在!");
            }
            if(StringUtils.isEmpty(company.getElectronicSeal())){

                throw new Exception("请配置分公司电子公章!");
            }
            // Loading an existing document
            //InputStream inFile = DigitalSignetService.class.getClassLoader().getResourceAsStream(SHIPPING_TEMPLATE_PATH);
            File inFile = new File(SHIPPING_TEMPLATE_PATH);
//            logger.info("draftShippingContract: 模板地址|{}", SHIPPING_TEMPLATE_PATH);
            PDDocument document = PDDocument.load(inFile);
            //添加水印----
            PdfEditUtil.addWaterMark(document,company.getCompanyName());

            String dateFormat = DateUtils.getDate("yyyy年MM月dd日");



            //第1页添加内容
            PDPageContentStream pageContentStream1 = getPDPageContentStream(document, 0);



//            String qiyexinxi=hySettingService.getSettingValueByTag("driver_shipping_template_watermark");
            OFFICIAL_SEAL = PATH_SUBFIX + company.getElectronicSeal();
            //甲方
            showTextByLeft(pageContentStream1,  company.getCompanyName(), "", 150,675);

            pageContentStream1.close();



            //第4页添加内容
            PDPageContentStream pageContentStream = getPDPageContentStream(document, 3);

            showTextByLeft(pageContentStream, joOrder.getString("orderNum"), "", 200,200 );
            //添加货物名称
            showTextByLeft(pageContentStream, joOrder.getString("descriptionOfGoods"), "", 200,170 );
            //添加货物总重量
            String goodsWeight = joOrder.getString("totalGoodsWeight") + joOrder.getString("goodsUnit_dictText");
            if(joOrder.getString("totalGoodsWeight")==null){
                showTextByLeft(pageContentStream, "-", "", 415,170 );
            }else{
                showTextByLeft(pageContentStream, goodsWeight, "", 415,170 );
            }

            //添加运费计算方式
            showTextByLeft(pageContentStream, joOrder.getString("shippingType_dictText"), "", 200,140 );
            //添加运费单价
//            String goodsPrice = joOrder.getString("shippingUnitPrice") + "元/" + joOrder.getString("goodsUnit_dictText");
//            shippingUnitPrice
            BigDecimal shippingUnitPrice = shippingNote.getShippingUnitPrice();
//            String goodsPrice = joOrder.getString("shippingUnitPrice")+ "元";
            showTextByLeft(pageContentStream, shippingUnitPrice.toString()+ "元", "", 415,140 );
            //添加亏损货物单价
//            String lossPrice = joOrder.getString("lossGoodsUnitPrice") + "元/" + joOrder.getString("goodsUnit_dictText");
            String lossPrice = joOrder.getString("lossGoodsUnitPrice") + "元";
            showTextByLeft(pageContentStream, lossPrice, "", 200,110 );
            //添加亏损免赔设置
            double lossProportion = joOrder.getDouble("lossProportion");
            String result = String.format("%.3f", lossProportion);
            String txt = joOrder.getString("lossType_dictText") + result;
            showTextByLeft(pageContentStream, txt, "", 415,110 );
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
            //装货时间
            if(shippingNote.getStatusDtLoading()!=null){
                showTextByLeft(pageContentStream, DateUtils.date2Str(shippingNote.getStatusDtLoading(),simpleDateFormat)  , "", 200,75 );
            }else{
                showTextByLeft(pageContentStream, dateFormat, "", 200,75 );
            }



            // Closing the content stream
            pageContentStream.close();


            //第5页添加内容
            PDPageContentStream pageContentStream2 = getPDPageContentStream(document, 4);

            //添加甲方单位公章
            addImage(pageContentStream2, document, OFFICIAL_SEAL, 130, 690);
            //添加乙方单位公章
//            addImage(pageContentStream2, document, "D:\\Administrator\\桌面\\123.jpg", 382, 690);
            //添加甲方签订日期
            showTextByLeft(pageContentStream2, dateFormat, "", 155,720);
            //添加乙方签订日期
            showTextByLeft(pageContentStream2, dateFormat, "", 408,720);

            // Closing the content stream
            pageContentStream2.close();

            String path = PATH_SUBFIX + SAVE_CONTRACT_ADDR;
            File fileDir = new File(path);
            if(!fileDir.exists()) {
                fileDir.mkdirs();//创建目录
            }
            contractPath = SAVE_CONTRACT_ADDR + SHIPPING_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
            String filename = PATH_SUBFIX + contractPath;
//            logger.info("draftShippingContract: path|{}", path);
//            logger.info("draftShippingContract: contractPath|{}", contractPath);
//            logger.info("draftShippingContract: filename|{}", filename);
            // Saving the document
            document.save(new File(filename));
            // Closing the document
            document.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return contractPath;
    }
    //司机签署车辆挂靠声明
    public Result<?> addSignetForVehicle(String filePath, String signetPath){
        String imagePath = "";
        //司机签名图片地址
        String driverSignPath = PATH_SUBFIX + signetPath;
        //司机签名图片 base64转图片
        //String driverSignPath = PATH_SUBFIX + SAVE_CONTRACT_ADDR + SIGNET_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + ".png";
//        logger.info("addSignetForVehicle: 司机签名图片地址|{}", driverSignPath);
        //ImageBase64Util.base64StringToImage(signetBase64, driverSignPath);
        try {
            File file = new File(PATH_SUBFIX + filePath);
//            logger.info("addSignetForVehicle: 加载挂靠声明合同地址|{}", file.getPath());
            PDDocument document = PDDocument.load(file);
//            if(document == null) {
//                return Result.error("加载挂靠声明失败");
//            }
            //第0页添加司机签名图片
            PDPageContentStream contentStream = getPDPageContentStream(document, 0);
//            if(contentStream == null) {
//                document.close();
//                return Result.error("无法从PDF文件中获取到第1页数据");
//            }
            //添加司机签名图片
            boolean addImg = addImage(contentStream, document, driverSignPath, 130, 330);
            // Closing the content stream
            contentStream.close();
//            logger.info("司机签名图片已添加");
            // 保存到源文件
            document.save(file);
            // Closing the document
            document.close();
            if(!addImg) {
                return Result.error("添加司机签名图片失败");
//                System.out.println("addSignetForVehicle 司机签署车辆挂靠声明 添加司机签名图片失败");
            }

            //PDF转图片
            String[] filename = filePath.split(VEHICLE_NAME_SUBFIX);
            filename = filename[1].split("\\.");
            List<String> srcList = PdfToImageUtil.pdf2Jpg(PATH_SUBFIX + SAVE_CONTRACT_ADDR, VEHICLE_NAME_SUBFIX + filename[0]);
            if(srcList.size() == 0 || srcList.get(0).equals("")){
                return Result.error("车辆挂靠声明PDF转图片失败！");
            }
            imagePath = SAVE_CONTRACT_ADDR + srcList.get(0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error("合同操作失败，1加载合同失败、2无法从合同获取需要签字的页");
        }
        return Result.OK(imagePath);
    }
    //司机签署运输协议
    public Result<?> addSignetForShipping(String filePath, String signetPath,String driverName){
        //司机签名图片 base64转图片
        String driverSignPath = PATH_SUBFIX + signetPath;
        //String driverSignPath = PATH_SUBFIX + SAVE_CONTRACT_ADDR + SIGNET_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + ".png";
//        logger.info("addSignetForShipping: 司机签名图片地址|{}", driverSignPath);
        //ImageBase64Util.base64StringToImage(signetBase64, driverSignPath);
        try {
            log.info("打开运输协议文件：{}, {}", driverName, PATH_SUBFIX + filePath);
            File file = new File(PATH_SUBFIX + filePath);
//            logger.info("addSignetForShipping: 加载运输协议地址|{}", file.getPath());
            PDDocument document = PDDocument.load(file);

            //第1页添加司机签名图片
            PDPageContentStream pageContentStream1 = getPDPageContentStream(document, 0);
            //乙方
            showTextByLeft(pageContentStream1, driverName, "", 150,635);
            pageContentStream1.close();

            //第5页添加司机签名图片
            PDPageContentStream page5ContentStream = getPDPageContentStream(document, 4);
            //添加司机签名图片
            addImage(page5ContentStream, document, driverSignPath, 382, 690);
            // Closing the content stream
            page5ContentStream.close();
//            logger.info("司机签名图片已添加");
            // Saving the document
            document.save(file);
            // Closing the document
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error("文件操作失败");
        }
        return Result.OK("运输协议签署成功");
    }


    //税务授权协议
//    public Result<?> addSignetForTax(String filePath, String signetPath){
//        //司机签名图片 base64转图片
//        String driverSignPath = PATH_SUBFIX + signetPath;
//        //String driverSignPath = PATH_SUBFIX + SAVE_CONTRACT_ADDR + SIGNET_NAME_SUBFIX + DateUtils.getDate("yyyyMMddHHmmss") + ".png";
////        logger.info("addSignetForShipping: 司机签名图片地址|{}", driverSignPath);
//        //ImageBase64Util.base64StringToImage(signetBase64, driverSignPath);
//        try {
//            File file = new File(PATH_SUBFIX + filePath);
////            logger.info("addSignetForShipping: 加载运输协议地址|{}", file.getPath());
//            PDDocument document = PDDocument.load(file);
//            //第1页添加司机签名图片
//            PDPageContentStream page5ContentStream = getPDPageContentStream(document, 0);
//            //添加司机签名图片
//            addImage(page5ContentStream, document, driverSignPath, 330, 330);
//            // Closing the content stream
//            page5ContentStream.close();
////            logger.info("司机签名图片已添加");
//            // Saving the document
//            document.save(file);
//            // Closing the document
//            document.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            return Result.error("文件操作失败");
//        }
//        return Result.OK("运输协议签署成功");
//    }

    public Result addSignetForLiaoningTax(HyDriver driver, String signetPath) throws IOException {

        List<HyCompany> companyList = hyCompanyService.list();
        if (companyList == null) {
            return Result.error("分公司信息不存在");
        }

        HyCompany company = companyList.get(0);
        if (StringUtils.isEmpty(company.getElectronicSeal())) {
            return Result.error("请配置分公司电子公章");
        }

        String pathSubfix = uploadpath + File.separator;
        //模板路径
        String shippingTemplatePath = pathSubfix + hySettingService.getSettingValueByTag("driver_tax_template");

        //输出路径
        String outputName2 = SAVE_CONTRACT_ADDR + SHIPPING_NAME_LXTAX + DateUtils.getDate("yyyyMMddHHmmss") + PDF_SUFFIX;
        String outputName = pathSubfix + outputName2;

        File fileDir = new File(pathSubfix + SAVE_CONTRACT_ADDR);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//创建目录
        }

        //乙方签名图片地址
        String yf_img = pathSubfix + signetPath;
        byte[] yfbytes = null;

        //甲方电子公章图片地址
        String jf_img = pathSubfix + company.getElectronicSeal();
        byte[] bytes = null;

        //图片的输入流
        FileInputStream fileInputStream = new FileInputStream(jf_img);
        bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        try {

            FileInputStream fileInputStream3 = new FileInputStream(shippingTemplatePath);

            //图片的输入流2
            FileInputStream fileInputStream2 = new FileInputStream(yf_img);
            yfbytes = new byte[fileInputStream2.available()];
            fileInputStream2.read(yfbytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputName));
            //读取pdf表单
            reader = new PdfReader(fileInputStream3);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();
            //给表单中添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();

            //乙方名称
            data.put("siji", driver.getDriverName());
            //住址
            data.put("address", driver.getAddress());
            data.put("telephone", driver.getTelephone());

            //甲方合同章
            data.put("jf_img", encoder.encode(bytes));

            //乙方签字章
            data.put("siji_img", encoder.encode(yfbytes));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            data.put("date", simpleDateFormat.format(new Date()));

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
//                //PDF转图片
//                String[] filename = outputName2.split(SHIPPING_NAME_LXTAX);
//                filename = filename[1].split("\\.");
//                List<String> srcList = PdfToImageUtil.pdf2Jpg(PATH_SUBFIX + SAVE_CONTRACT_ADDR, SHIPPING_NAME_LXTAX + filename[0]);
//                if(srcList.size() == 0 || srcList.get(0).equals("")){
//                    return Result.error("生成税务授权协议失败！");
//                }
//
//                outputName2 = SAVE_CONTRACT_ADDR + srcList.get(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return Result.OK(outputName2);
    }

}
